package org.xtown.bingluo.xtieba.ui.activities;

import java.io.IOException;

import org.xtown.bingluo.xtieba.R;
import org.xtown.bingluo.xtieba.appinfo.SettingInfo;
import org.xtown.bingluo.xtieba.controllers.Controller;
import org.xtown.bingluo.xtieba.db.XtiebaAuthorDb;
import org.xtown.bingluo.xtieba.db.XtiebaPostsDb;
import org.xtown.bingluo.xtieba.db.XtiebaPostsInfoDb;
import org.xtown.bingluo.xtieba.standby.Constants;
import org.xtown.bingluo.xtieba.utils.IOUtils;
import org.xtown.bingluo.xtieba.utils.LogUtlils;
import org.xtown.bingluo.xtieba.utils.UiUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;

public class BaseActivity extends Activity {
	
	protected int screenHeight;
	protected int screenWidth;
	protected AlertDialog dlg;
	public static final int ID_EXIT_DIALOG = 99;

	public boolean isDialog = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		System.out.println(getClass().getName().toString() + " - onCreate");
		super.onCreate(savedInstanceState);
		Constants.initializeConstantsFromResources(this);

		Controller.getInstance().setPreferences(
				PreferenceManager.getDefaultSharedPreferences(this));
		SettingInfo.setSettingInfo(this);

		if (Controller.getInstance().getPreferences()
				.getBoolean(Constants.PREFERENCES_SHOW_FULL_SCREEN, false)) {
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}

		if (Controller
				.getInstance()
				.getPreferences()
				.getBoolean(Constants.PREFERENCES_GENERAL_HIDE_TITLE_BARS, true)) {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
		}
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		screenHeight = display.getHeight();
		screenWidth = display.getWidth();
		UiUtils.settingScreenOrientation(this, SettingInfo.m_autohorscreem_v);
		Constants.initializeConstantsFromResources(this);
		Constants.initializeConstantsFromSharedPreferences(this);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		Log.v("onConfigurationChanged", "do");
	}

	// ////////////////////menu S//////////////////////////////////////////
	// 点击Menu时，系统调用当前Activity的onCreateOptionsMenu方法，并传一个实现了一个Menu接口的menu对象供你使用
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// return true才会起作用
		return true;

	}

	// 菜单项被选择事件
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return false;
	}

	// 选项菜单被关闭事件，菜单被关闭有三种情形，menu按钮被再次点击、back按钮被点击或者用户选择了某一个菜单项
	@Override
	public void onOptionsMenuClosed(Menu menu) {
		// Toast.makeText(this, "选项菜单关闭了", Toast.LENGTH_LONG).show();
	}

	// 菜单被显示之前的事件
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// Toast.makeText(this,
		// "选项菜单显示之前onPrepareOptionsMenu方法会被调用，你可以用此方法来根据打当时的情况调整菜单",
		// Toast.LENGTH_LONG).show();
		// 如果返回false，此方法就把用户点击menu的动作给消费了，onCreateOptionsMenu方法将不会被调用
		return true;
	}

	// ////////////////////menu E//////////////////////////////////////////

	// ////////////////////exit S//////////////////////////////////////////
	// 写一个广播的内部类，当收到动作时，结束activity
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("广播--------------");
			((Activity) context).finish();
			// 退出后台线程,以及销毁静态变量(会在主activity的onDestroy执行System.exit(0);)
		}
	};

	/**
	 * 关闭
	 */
	public void close() {
		System.out.println("关闭程序--------------" + getClass().getName());
		Intent intent = new Intent();
		intent.setAction(Constants.EXIT_ACTION); // 说明动作
		sendBroadcast(intent);// 该函数用于发送广播
		finish();
		// 退出后台线程,以及销毁静态变量
		// System.exit(0);
	}

	public void isExit() {
		showDialog(ID_EXIT_DIALOG);
	}

	// ////////////////////exit E//////////////////////////////////////////

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			System.out.println("dddddd");
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
		System.out.println(getClass().getName() + " - onPause");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		System.out.println(getClass().getName() + " - onDestroy");
		// 这句话必须要写要不会报错，不写虽然能关闭，会报一堆错
		unregisterReceiver(this.broadcastReceiver);
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		System.out.println(getClass().getName() + " - onRestart");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println(getClass().getName() + " - onResume");

		// 在当前的activity中注册广播
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.EXIT_ACTION);
		registerReceiver(this.broadcastReceiver, filter); // 注册
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		System.out.println(getClass().getName() + " - onStart");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		System.out.println(getClass().getName() + " - onStop");
	}
	
	protected void clearAllPosts(final Handler handler, final int msgWhat) {
		new Thread(){
			public void run() {
				Boolean r = true;
				XtiebaPostsInfoDb.getNetInstance(BaseActivity.this).deleteAll();
				XtiebaPostsDb.getNetInstance(BaseActivity.this).deleteAll();
				XtiebaAuthorDb.getNetInstance(BaseActivity.this).deleteAll();
				try {
					String pSd = IOUtils.getAvatarPathInSd(BaseActivity.this);
					if (!pSd.equals("")) {
						LogUtlils.println("pSd="+pSd);
						IOUtils.delFile(pSd);
					}
					String pFiles = IOUtils.getAvatarPathInFiles(BaseActivity.this);
					if (!pFiles.equals("")) {
						LogUtlils.println("pFiles="+pFiles);
						IOUtils.delFile(pFiles);
					}
				} catch (IOException e) {
					e.printStackTrace();
					r = false;
				}
				Message msg = handler.obtainMessage();
				msg.what = msgWhat;
				msg.obj = r;
				handler.sendMessage(msg);
			};
		}.start();
	}
	
	// 创建简单Dialog
	public Dialog createExitDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.AreYouSureExit)
				.setCancelable(false)
				.setPositiveButton(R.string.Commons_Yes,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								BaseActivity.this.close();
							}
						})
				.setNegativeButton(R.string.Commons_No, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		return alert;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case ID_EXIT_DIALOG:
			dialog = createExitDialog();
			break;
		default:
			break;
		}
		if (dialog != null) {
		} else {
		}
		return dialog;
	}
	
	protected void updateUI(Object commandObject) {
		
	}
}
